package com.yangming.springboot.deepin.playTest;

import com.yangming.springboot.deepin.Application;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @创建人 ym
 * @创建时间 2021/4/1 0001
 * @描述
 **/
@SpringBootTest(classes = {Application.class})
public class concurrencyTest {
    //private static 和 private 的区别就在于，前者可以通过concurrencyTest.count访问，后者不可以
    private static long count = 1000001;

    public static void main(String[] args) throws InterruptedException{
        concurrency();
        serial();

        System.out.println(concurrencyTest.count);
    }
//    多线程并发，计算10万次的并行计算,由于并行计算带来的线程创建与切换上下文带来的额外开销，并行计算的执行速度反而比串行计算要慢一些
    public static void concurrency() throws InterruptedException{
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i<count; i++){
                    a += 5;
                }
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i< count ; i++){
            b--;
        }
        long time = System.currentTimeMillis() - start;
        thread.join();
        System.out.println("concurrency :" + time + "ms" + "b=" + b);
    }
//    单线程计算
    public static void serial(){
        long start = System.currentTimeMillis();
        int a = 0;
        for (long i = 0; i< count; i++){
            a += 5;
        }
        int b = 0;
        for (long i = 0; i< count; i++){
            b--;
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("serial : " + time + "ms" + "b=" + b);
    }
}
